package com.concurrent.aqslock.part10.aqs;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 类说明：实现一个自己的锁
 */
public class SelfLock implements Lock {

    /**
     * state 表示获取到锁 state=1 获取到了锁，state=0，表示这个锁当前没有线程拿到
     */
    private static class Sync extends AbstractQueuedSynchronizer {

        /**
         * 当前锁是否被占用
         */
        @Override
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }

        /**
         * 独占式获取锁
         */
        @Override
        protected boolean tryAcquire(int arg) {
            // 使用CAS设置state设置当前拥有锁的线程
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        @Override
        protected boolean tryRelease(int arg) {
            // 如果state已经为0则不需释放
            if (getState() == 0) {
                throw new UnsupportedOperationException();
            }
            setExclusiveOwnerThread(null);
            // 这里不使用CAS的原因是这个是独占锁，释放锁的时候不会出现并发问题
            setState(0);
            return true;
        }

        Condition newCondition() {
            return new ConditionObject();
        }
    }

    private final Sync sycn = new Sync();

    @Override
    public void lock() {
        sycn.acquire(1);

    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        sycn.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return sycn.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sycn.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        sycn.release(1);

    }

    @Override
    public Condition newCondition() {
        return sycn.newCondition();
    }

    /**
     * 简单的测试线程，打印出获取到锁的线程名称，并sleep2秒
     */
    private static class TestMyLock implements Runnable {
        Lock lock;

        public TestMyLock(Lock selfLock) {
            lock = selfLock;
        }

        @Override
        public void run() {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " get the lock and will sleep 2 second");
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] arg0) {
        Lock selfLock = new SelfLock();
        for (int i = 0; i < 3; ++i) {
            new Thread(new TestMyLock(selfLock), "Test self Lock Thread: " + i).start();
        }

        Lock reentrantLock = new ReentrantLock();
        for (int i = 0; i < 3; ++i) {
            new Thread(new TestMyLock(reentrantLock), "ReentrantLock Thread: " + i).start();
        }
    }

}
